const MYSQL = require("../../sql/mysql");
const Redis = require("../../sql/redis");
const { formatMenusList, formatTreeList } = require("../../utils/format");
/**
 * 获取APP管理系统路由列表
 * @return {promise<{code:string,msg:string}>}
 */
async function GetAppAdminRouterList(Request) { }
/**
 * 获取PC管理系统路由列表(一维数组)
 * @return {promise<{code:string,msg:string}>}
 */
async function GetV1AdminRouterList(Request) {
    try {
        let user = Request.$user;

        let roles = Request.$roles;

        let RoleMysqlQuery = `
			SELECT menus.* FROM menus
			JOIN  auth_role_menu ON 
				auth_role_menu.menu_id = menus.id
			JOIN  auth_role ON 
				auth_role_menu.role_id = auth_role.id AND
				auth_role.state = 1
			WHERE auth_role_menu.role_id IN(${roles})
		`;
        // 获取Mysql池连接
        let conn = await MYSQL.promise().getConnection();
        // 开始查询MYSQL数据
        let Rolelist = await conn.query(RoleMysqlQuery);
        // 查询完毕，释放池连接回池
        await conn.release();
        // 处理数据
        let RoleMenuList = Rolelist[0];
        let list = formatMenusList(RoleMenuList);
        let total = list.length;
        return {
            code: 0,
            msg: "操作成功",
            data: {
                user,
                total,
                roles,
                list,
            },
        };
    } catch (error) {
        console.log(error);
        throw {
            code: 500,
            msg: "获取菜单列表失败",
        };
    }
}
/**
 * 获取PC管理系统路由列表(二维数组)
 * @return {promise<{code:string,msg:string}>}
 */
async function GetV2AdminRouterList(Request) {
    try {
        let user = Request.$user;

        let roles = Request.$roles;

        let MysqlQuery = `
			SELECT menus.* FROM menus
			JOIN  auth_role_menu ON 
				auth_role_menu.menu_id = menus.id
			JOIN  auth_role ON 
				auth_role_menu.role_id = auth_role.id AND
				auth_role.state = 1
			WHERE auth_role_menu.role_id IN(${roles})
		`;
        // 获取Mysql池连接
        let conn = await MYSQL.promise().getConnection();
        // 开始查询MYSQL数据
        let [list] = await conn.query(MysqlQuery);
        // 查询完毕，释放池连接回池
        await conn.release();
        let ArrayFormatVueRouter = (
            array,
            pid = null,
            parentStorey = null
        ) => {
            return array.reduce((prev, cur) => {
                if (Number(cur.meta.pid) == Number(pid)) {
                    let Storey = parentStorey ?? 0;
                    let meta = cur.meta;
                    cur.meta.Storey = Storey;
                    const children = ArrayFormatVueRouter(array, meta.id, ++Storey);
                    cur.children = children;
                    prev.push(cur);
                }
                return prev;
            }, []);
        };
        // 所有数据转VueRouter格式
        list = formatMenusList(list);
        let TreeList = ArrayFormatVueRouter(list).filter(i => {
            if (i.meta.pid) {
                return false
            } else {
                return true
            }
        })
        return {
            code: 0,
            msg: "操作成功",
            data: TreeList
        };
    } catch (error) {
        console.log(error);

        throw {
            code: 500,
            msg: "获取菜单列表失败",
        };
    }
}
/*
* 获取NaiveAdmin 菜单列表
*/
async function NavieAdminRouterList(Request) {
    try {
        let user = Request.$user;
        // 获取MYSQL 实例
        let conn = await MYSQL.promise().getConnection();
        let SqlName = "navie_router"
        // 开始查询MYSQL数据
        let [list] = await conn.query(`SELECT * FROM ${SqlName} WHERE state = 1`);

        list = list.map(item => {
            let {
                show, enable
            } = item
            item.show = Boolean(show)
            item.enable = Boolean(enable)
            return item
        })

        // 转成树状结构
        let formatMenusList = (list) => {
            let result = [];
            let map = {};
            list.forEach((item) => {
                map[item.id] = item;
            });
            list.forEach((item) => {
                let parent = map[item.parentId];
                if (parent) {
                    (parent.children || (parent.children = [])).push(item);
                } else {
                    result.push(item);
                }
            });
            return result;
        };
        list = formatMenusList(list);
        // 查询完毕，释放池连接回池
        await conn.release();
        return {
            code: 0, msg: "操作成功", data: {
                list
            }
        }
    } catch (error) {
        throw {
            code: 500,
            msg: "获取菜单列表失败",
        };
    }
}
/**
 * 获取管理系统个性化配置对象
 * @return {promise<{code:string,msg:string}>}
 */
async function GetAdminCustomize(Request) {
    try {
        let user = Request.$user;

        let RedisPath = `${ProjectName}:user:Custom:${user}`;

        let Customize = (await Redis.get(RedisPath)) ?? {};

        return {
            code: 0,
            msg: "操作成功",
            data: JSON.parse(Customize),
        };
    } catch (error) {
        console.log(error);
        throw {
            code: 500,
            msg: "获取失败",
        };
    }
}
/**
 * 更新管理系统个性化配置对象
 * @return {promise<{code:string,msg:string}>}
 */
async function UpdateAdminCustomize(Request) { }
/**
 * 保存个性化配置
 * @return {promise<{code:string,msg:string}>}
 */
async function SaveAdminCustomize(Request) {
}
/**
 * 获取个性化配置
 */
async function GetAdminCustomizeConfig(Request) {
}
// 导出所有
module.exports = {
    NavieAdminRouterList,
    GetAppAdminRouterList,
    GetV1AdminRouterList,
    GetV2AdminRouterList,
    GetAdminCustomize,
    UpdateAdminCustomize,
};
